import { defineStore } from 'pinia'
import axios from 'axios'

export const useBlogStore = defineStore('blog', {
  state: () => ({
    blogs: [],
    blogTypes: [],
    currentBlog: null,
    loading: false,
    error: null,
    totalPages: 1,
    currentPage: 1
  }),
  
  getters: {
    getBlogById: (state) => (id) => {
      return state.blogs.find(blog => blog.blogId === id) || null
    },
    
    getBlogTypeById: (state) => (id) => {
      return state.blogTypes.find(type => type.typeId === id) || null
    }
  },
  
  actions: {
    async fetchBlogs(page = 1, size = 10, query = '') {
      this.loading = true
      try {
        const response = await axios.get('/api/blog/list', {
          params: { 
            pageNum: page, 
            pageSize: size, 
            query 
          }
        })
        if (response.data) {
          this.blogs = response.data.content.map(blog => ({
            ...blog,
            id: blog.blogId // 为了兼容性添加 id 字段
          }))
          this.totalPages = Math.ceil(response.data.total / size)
          this.currentPage = page
        } else {
          this.blogs = []
          this.totalPages = 1
          this.currentPage = 1
        }
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '获取博客列表失败'
        this.blogs = []
        this.totalPages = 1
        this.currentPage = 1
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async fetchBlogsByType(typeId, page = 1, size = 10) {
      this.loading = true
      try {
        const response = await axios.get('/api/blog/list', {
          params: { 
            pageNum: page, 
            pageSize: size, 
            typeId 
          }
        })
        if (response.data) {
          this.blogs = response.data.content.map(blog => ({
            ...blog,
            id: blog.blogId
          }))
          this.totalPages = Math.ceil(response.data.total / size)
          this.currentPage = page
        } else {
          this.blogs = []
          this.totalPages = 1
          this.currentPage = 1
        }
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '获取分类博客失败'
        this.blogs = []
        this.totalPages = 1
        this.currentPage = 1
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async fetchUserBlogs(userId, page = 1, size = 10) {
      this.loading = true
      try {
        const response = await axios.get(`/api/blog/user/${userId}`, {
          params: { page, size }
        })
        this.blogs = response.data.content
        this.totalPages = response.data.totalPages
        this.currentPage = page
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '获取用户博客失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async fetchBlogById(id) {
      this.loading = true
      try {
        console.log(`开始获取博客详情，ID: ${id}`)
        const url = `/api/blog/${id}`
        console.log(`请求URL: ${url}`)
        
        const response = await axios.get(url)
        console.log('获取博客详情响应:', response)
        
        // 服务器响应不成功
        if (!response.data.success) {
          console.error('服务器返回错误:', response.data.message)
          throw new Error(response.data.message || '无法获取博客')
        }
        
        const blogData = response.data.blog || response.data;
        console.log('解析后的博客数据:', blogData)
        
        if (!blogData || !blogData.blogId) {
          console.error('博客数据无效:', blogData)
          throw new Error('无效的博客数据')
        }
        
        this.currentBlog = {
          ...blogData,
          id: blogData.blogId  // 添加 id 属性以兼容前端代码
        }
        return this.currentBlog
      } catch (error) {
        console.error('获取博客详情失败:', error)
        console.error('错误详情:', error.response || error.message || error)
        this.error = error.response?.data?.message || '获取博客详情失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async fetchBlogTypes() {
      this.loading = true
      try {
        const response = await axios.get('/api/blog/types')
        this.blogTypes = response.data.map(type => ({
          ...type,
          id: type.typeId
        }))
        return this.blogTypes
      } catch (error) {
        this.error = error.response?.data?.message || '获取博客分类失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async createBlog(blogData) {
      this.loading = true
      try {
        const response = await axios.post('/api/blog/create', blogData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '创建博客失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async updateBlog(id, blogData) {
      this.loading = true
      try {
        const response = await axios.put(`/api/blog/update/${id}`, blogData)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '更新博客失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async deleteBlog(id) {
      this.loading = true
      try {
        const response = await axios.delete(`/api/blog/delete/${id}`)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '删除博客失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    
    async likeBlog(blogId) {
      try {
        const response = await axios.post(`/api/blog/${blogId}/like`)
        return response.data
      } catch (error) {
        this.error = error.response?.data?.message || '点赞失败'
        throw error
      }
    }
  }
}) 